package org.advanced.expand;

/**
 * @author John.zhang
 * @version Id: TransAccountC, v 1.0 2020/12/11 17:18 ZhiYong Exp $
 * hashcode排序破坏死锁，但是没有解决转账问题(破坏循坏等待的问题)
 */
public class TransAccountC implements Runnable {

    private Account fromAccount;

    private Account toAccount;

    private int amount;

    public TransAccountC(Account fromAccount, Account toAccount, int amount) {
        this.fromAccount = fromAccount;
        this.toAccount = toAccount;
        this.amount = amount;
    }

    @Override
    public void run() {
        Account left = null;
        Account right = null;
        if(fromAccount.hashCode()>toAccount.hashCode()){
            left = toAccount;
            right = fromAccount;
        }
        while (true) {
            synchronized (left) {
                synchronized (right) {
                    if (fromAccount.getBalance() >= amount) {
                        fromAccount.debit(amount);
                        toAccount.credit(amount);
                    }
                }
                System.out.println(fromAccount.getAccountName() + "-" + fromAccount.getBalance());
                System.out.println(toAccount.getAccountName() + "-" + toAccount.getBalance());
            }
        }
    }


    public static void main(String[] args) {
        Account fromAccount = new Account("张三", 100000);
        Account toAccount = new Account("李四", 200000);

        Thread threadA = new Thread(new TransAccountC(fromAccount, toAccount, 1));
        Thread threadB = new Thread(new TransAccountC(toAccount, fromAccount, 1));
        threadA.start();
        threadB.start();
    }

}
